package name.huzhenbo.java.patterns.builder;

/**
 * Effective Java, Item 2: consider a builder when faced with many constructor parameters.
 * <p/>
 * 1. the telescoping constructor pattern works, but it is hard to write
 * client code when there are many parameters, and harder still to read it.
 * <p/>
 * 2. The JavaBeans pattern has serious disadvantages of its own.
 * Because construction is split across multiple calls (set method), a JavaBean may be in an
 * inconsistent state partway through its construction.  The JavaBeans pattern pre-
 * cludes the possibility of making a class immutable
 * <p/>
 * The Builder pattern simulates named optional parameters
 * <p/>
 * In summary, the Builder pattern is a good choice when designing classes
 * whose constructors or static factories would have more than a handful of
 * parameters, especially if most of those parameters are optional. Client code is
 * much easier to read and write with builders than with the traditional telescoping
 * constructor pattern, and builders are much safer than JavaBeans.
 */
class NutritionFacts {
    private int servingSize;
    private int servings;
    private int calories;
    private int sodium;
    private int carbohydrate;


    public NutritionFacts(Builder builder) {
        this.servingSize = builder.servingSize;
        this.servings = builder.servings;
        this.calories = builder.calories;
        this.sodium = builder.sodium;
        this.carbohydrate = builder.carbohydrate;
    }

    public static class Builder implements name.huzhenbo.java.patterns.builder.Builder<NutritionFacts> {
        // Required parameters
        private int servingSize;
        private int servings;

        // Optional parameters
        private int calories;
        private int sodium;
        private int carbohydrate;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }


        public Builder calories(int calories) {
            this.calories = calories;
            return this;
        }

        public Builder sodium(int sodium) {
            this.sodium = sodium;
            return this;
        }


        public Builder carbohydrate(int carbohydrate) {
            this.carbohydrate = carbohydrate;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    public int getServingSize() {
        return servingSize;
    }

    public int getServings() {
        return servings;
    }

    public int getCalories() {
        return calories;
    }

    public int getSodium() {
        return sodium;
    }

    public int getCarbohydrate() {
        return carbohydrate;
    }
}
